package cn.iocoder.yudao.module.product.job;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.product.controller.admin.spu.vo.ProductSkuSaveReqVO;
import cn.iocoder.yudao.module.product.controller.admin.spu.vo.ProductSpuSaveReqVO;
import cn.iocoder.yudao.module.product.dal.dataobject.resourceshare.ResourceShareDO;
import cn.iocoder.yudao.module.product.dal.dataobject.sku.ProductSkuDO;
import cn.iocoder.yudao.module.product.dal.dataobject.spu.ProductSpuDO;
import cn.iocoder.yudao.module.product.dal.mysql.resourceshare.ResourceShareMapper;
import cn.iocoder.yudao.module.product.dal.mysql.sku.ProductSkuMapper;
import cn.iocoder.yudao.module.product.dal.mysql.spu.ProductSpuMapper;
import cn.iocoder.yudao.module.product.enums.spu.ProductSpuStatusEnum;
import cn.iocoder.yudao.module.product.job.luoqi.ResourceShare;
import cn.iocoder.yudao.module.product.job.luoqi.ResourceShareSource;
import cn.iocoder.yudao.module.product.job.luoqi.ResultDeatil;
import cn.iocoder.yudao.module.product.job.luoqi.ResultLuoQI;
import cn.iocoder.yudao.module.product.job.utils.HttpUtils;
import cn.iocoder.yudao.module.product.service.brand.ProductBrandService;
import cn.iocoder.yudao.module.product.service.category.ProductCategoryService;
import cn.iocoder.yudao.module.product.service.sku.ProductSkuService;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.getMinValue;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.getSumValue;

/**
 * 定时查询共享资源里的数据，并且保存到spu表中
 */
@Component
@Slf4j
public class ResourceShareSpuJob implements JobHandler {

    @Resource
    private ProductSpuMapper productSpuMapper;

    @Resource
    @Lazy // 循环依赖，避免报错
    private ProductSkuService productSkuService;
    @Resource
    private ProductBrandService brandService;

    @Resource
    private ResourceShareMapper resourceShareMapper;

    @Resource
    private ProductSkuMapper productSkuMapper;

    @Override
    @TenantJob // 标记多租户
    public String execute(String param) {
        log.info("定时任务开始查询数据资源");
        for (int i = 0; i < Long.parseLong(param); i++) {
            log.info("###【定时任务开始查询数据资源,查询页数为:{}】###", i);
            String url = "https://xcx.you123.top/api/v2/fuyehome/getResourceList?pageNum=" + i;
            String get = HttpUtils.sendGet(url);
            ResultLuoQI<ResourceShareSource> resultLuoQi = JSONObject.parseObject(get, new TypeReference<ResultLuoQI<ResourceShareSource>>() {
            });
            List<ResourceShareSource> data = resultLuoQi.getData();
            if (ObjectUtils.isEmpty(data)) {
                log.info("数据为空,结束循环");
                break; // 结束循环，避免后续代码执行
            }
            log.info("###【捕捉到数据不为空,开始进行保存操作!】###");
            for (ResourceShareSource datum : data) {
                try {
                    String url1 = "https://xcx.you123.top/api/v2/fuyehome/getDetail?resourceId=" + datum.getResourceId() + "&token=";
                    String get1 = HttpUtils.sendGet(url1);
                    ResultDeatil resultDeatil = JSONObject.parseObject(get1, new TypeReference<ResultDeatil>() {
                    });
                    cn.iocoder.yudao.module.product.job.luoqi.ResourceDate resourceDate = resultDeatil.getData();
                    ResourceShareSource resource = resourceDate.getResource();
                    ResourceShare share = new ResourceShare();
                    org.springframework.beans.BeanUtils.copyProperties(resource, share);
                    ResourceShareDO resourceShare = cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(share, ResourceShareDO.class);
                    ResourceShareDO shareDO = resourceShareMapper.selectByResourceId(resourceShare.getResourceId());
                    if (ObjectUtils.isEmpty(shareDO)) {
                        log.info("数据为空,开始进行添加,数据为:{}", resourceShare);
                        resourceShareMapper.insert(resourceShare);
                    }
                } catch (Exception e) {
                    log.error("处理数据时发生异常", e);
                }
            }
        }
        log.info("开始进行定时查询共享资源里的数据，并且保存到spu表中");
        List<ResourceShareDO> resourceShareDOList = resourceShareMapper.selectList();
        for (ResourceShareDO resourceShareDO : resourceShareDOList) {
            long categoryId;
            switch (resourceShareDO.getCategoryId()) {
                case 14: //实战项目
                    categoryId=61L;
                    createProductSpu(resourceShareDO, categoryId);
                    break;
                case 15: //短视频
                    categoryId=63L;
                    createProductSpu(resourceShareDO, categoryId);
                    break;
                case 16: //引流推广
                    categoryId=65L;
                    createProductSpu(resourceShareDO, categoryId);
                    break;
                case 17: //电商运营
                    categoryId=67L;
                    createProductSpu(resourceShareDO, categoryId);
                    break;
                case 18: //文案写作
                    categoryId=69L;
                    createProductSpu(resourceShareDO, categoryId);
                    break;
                case 19: //自媒体
                    categoryId=71L;
                    createProductSpu(resourceShareDO, categoryId);
                    break;
                case 20: //社群营销
                    categoryId=73L;
                    createProductSpu(resourceShareDO, categoryId);
                    break;
                case 21: //其它
                    categoryId=75L;
                    createProductSpu(resourceShareDO, categoryId);
                    break;
                case 22: //免费资源
                    categoryId=77L;
                    createProductSpu(resourceShareDO, categoryId);
                    break;
                default:
                    categoryId = 61L;
                    createProductSpu(resourceShareDO, categoryId);
                    break;
            }
        }
        return "success";
    }

//    public String execute(String param) {
//        log.info("定时任务开始查询数据资源");
//        for (int i = 0; i < 50; i++) {
//            log.info("###【定时任务开始查询数据资源,查询页数为:{}】###",i);
//            String url = "https://xcx.you123.top/api/v2/fuyehome/getResourceList?pageNum=" + i;
//            String get = HttpUtils.sendGet(url);
//            ResultLuoQI<ResourceShareSource> resultLuoQi = JSONObject.parseObject(get, new TypeReference<ResultLuoQI<ResourceShareSource>>() {
//            });
//            List<ResourceShareSource> data = resultLuoQi.getData();
//            if (ObjectUtils.isEmpty(data)) {
//                return "数据为空,结束循环";
//            }
//            log.info("###【捕捉到数据不为空,开始进行保存操作!】###");
//            for (ResourceShareSource datum : data) {
//                String url1 = "https://xcx.you123.top/api/v2/fuyehome/getDetail?resourceId=" + datum.getResourceId() + "&token=";
//                String get1 = HttpUtils.sendGet(url1);
//                ResultDeatil resultDeatil = JSONObject.parseObject(get1, new TypeReference<ResultDeatil>() {});
//                cn.iocoder.yudao.module.product.job.luoqi.ResourceDate resourceDate = resultDeatil.getData();
//                ResourceShareSource resource = resourceDate.getResource();
//                ResourceShare share = new ResourceShare();
//                org.springframework.beans.BeanUtils.copyProperties(resource, share);
//                ResourceShareDO resourceShare = cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(share, ResourceShareDO.class);
//                ResourceShareDO shareDO = resourceShareMapper.selectByResourceId(resourceShare.getResourceId());
//                if (ObjectUtils.isEmpty(shareDO)) {
//                    log.info("数据为空,开始进行添加,数据为:{}",resourceShare);
//                    resourceShareMapper.insert(resourceShare);
//                }
//            }
//
//        }
//        log.info("开始进行定时查询共享资源里的数据，并且保存到spu表中");
//        List<ResourceShareDO> resourceShareDOList = resourceShareMapper.selectList();
//        for (ResourceShareDO resourceShareDO : resourceShareDOList) {
//            long categoryId;
//            switch (resourceShareDO.getCategoryId()){
//                case 14: //实战项目
//                    categoryId=61L;
//                    createProductSpu(resourceShareDO, categoryId);
//                    break;
//                case 15: //短视频
//                    categoryId=63L;
//                    createProductSpu(resourceShareDO, categoryId);
//                    break;
//                case 16: //引流推广
//                    categoryId=65L;
//                    createProductSpu(resourceShareDO, categoryId);
//                    break;
//                case 17: //电商运营
//                    categoryId=67L;
//                    createProductSpu(resourceShareDO, categoryId);
//                    break;
//                case 18: //文案写作
//                    categoryId=69L;
//                    createProductSpu(resourceShareDO, categoryId);
//                    break;
//                case 19: //自媒体
//                    categoryId=71L;
//                    createProductSpu(resourceShareDO, categoryId);
//                    break;
//                case 20: //社群营销
//                    categoryId=73L;
//                    createProductSpu(resourceShareDO, categoryId);
//                    break;
//                case 21: //其它
//                    categoryId=75L;
//                    createProductSpu(resourceShareDO, categoryId);
//                    break;
//                case 22: //免费资源
//                    categoryId=77L;
//                    createProductSpu(resourceShareDO, categoryId);
//                    break;
//                default:
//                    categoryId=61L;
//                    createProductSpu(resourceShareDO, categoryId);
//                    break;
//            }
//        }
//        return "success";
//    }

    public  List<ProductSkuSaveReqVO> productSkuSave(ResourceShareDO resourceShareDO){
        List<ProductSkuSaveReqVO> skus = new ArrayList<>();

        ProductSkuSaveReqVO productSkuSaveReqVO = new ProductSkuSaveReqVO();
        productSkuSaveReqVO.setName(resourceShareDO.getTitle());
        productSkuSaveReqVO.setPrice(999);
        productSkuSaveReqVO.setMarketPrice(99999);
        productSkuSaveReqVO.setCostPrice(0);
        productSkuSaveReqVO.setBarCode(resourceShareDO.getResourceId().toString());
        productSkuSaveReqVO.setPicUrl(resourceShareDO.getShowCoverImage());
        productSkuSaveReqVO.setStock(999);
        productSkuSaveReqVO.setWeight(0.0);
        productSkuSaveReqVO.setVolume(0.0);

        List<ProductSkuSaveReqVO.Property> properties = new ArrayList<>();
        ProductSkuSaveReqVO.Property property = new ProductSkuSaveReqVO.Property();
        property.setPropertyId(0L);
        property.setPropertyName("默认");
        property.setValueId(0L);
        property.setValueName("默认");
        properties.add(property);

        productSkuSaveReqVO.setProperties(properties);
        skus.add(productSkuSaveReqVO);
        return skus;
    }


    public ProductSpuSaveReqVO createProductSpu(ResourceShareDO resourceShareDO, Long categoryId) {
        ProductSpuSaveReqVO createReqVO = new ProductSpuSaveReqVO();
        createReqVO.setName(resourceShareDO.getTitle());
        createReqVO.setKeyword(resourceShareDO.getTitle().substring(0, 5));
        createReqVO.setIntroduction(resourceShareDO.getTitle().substring(0, Math.min(10, resourceShareDO.getTitle().length())));
        createReqVO.setDescription(resourceShareDO.getContent());
        createReqVO.setCategoryId(categoryId);
        createReqVO.setBrandId(4L);
        createReqVO.setPicUrl(resourceShareDO.getShowCoverImage());

        List<String> sliderPicUrls = new ArrayList<>();
        sliderPicUrls.add(resourceShareDO.getShowCoverImage());
        createReqVO.setSliderPicUrls(sliderPicUrls);

        createReqVO.setSort(0);
        createReqVO.setSpecType(true);

        List<Integer> deliveryTypes = new ArrayList<>();
        deliveryTypes.add(1);
        createReqVO.setDeliveryTypes(deliveryTypes);

        createReqVO.setDeliveryTemplateId(1L);
        createReqVO.setGiveIntegral(10);
        createReqVO.setSubCommissionType(true);

        Random random = new Random();
        int virtualSalesCount = random.nextInt(100);
        int salesCount = random.nextInt(100);
        int browseCount = random.nextInt(100);
        createReqVO.setVirtualSalesCount(virtualSalesCount);
        createReqVO.setSalesCount(salesCount);
        createReqVO.setBrowseCount(browseCount);
        List<ProductSkuSaveReqVO> productSkuSaveReqVOS = productSkuSave(resourceShareDO);
        createReqVO.setSkus(productSkuSaveReqVOS);

        Instant instant = Instant.ofEpochMilli(resourceShareDO.getPutTime());
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        createReqVO.setPutTime(localDateTime);

        brandService.validateProductBrand(4L);
        ProductSpuDO spu = BeanUtils.toBean(createReqVO, ProductSpuDO.class);
        // 初始化 SPU 中 SKU 相关属性
        initSpuFromSkus(spu, productSkuSaveReqVOS);
        // 插入 SPU
        spu.setCreateTime(createReqVO.getPutTime());


        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("bar_code",resourceShareDO.getResourceId());

        ProductSkuDO productSkuDO = productSkuMapper.selectOne(wrapper);
        if (ObjectUtil.isEmpty(productSkuDO)){
            log.info("开始保存数据:{}",resourceShareDO.getResourceId());
            productSpuMapper.insert(spu);
            // 插入 SKU
            productSkuService.createSkuList(spu.getId(), productSkuSaveReqVOS);
        }else {
            log.info("数据已经存在:{}",resourceShareDO.getResourceId());
        }

        return createReqVO;
    }


    /**
     * 基于 SKU 的信息，初始化 SPU 的信息
     * 主要是计数相关的字段，例如说市场价、最大最小价、库存等等
     *
     * @param spu  商品 SPU
     * @param skus 商品 SKU 数组
     */
    private void initSpuFromSkus(ProductSpuDO spu, List<ProductSkuSaveReqVO> skus) {
        // sku 单价最低的商品的价格
        spu.setPrice(getMinValue(skus, ProductSkuSaveReqVO::getPrice));
        // sku 单价最低的商品的市场价格
        spu.setMarketPrice(getMinValue(skus, ProductSkuSaveReqVO::getMarketPrice));
        // sku 单价最低的商品的成本价格
        spu.setCostPrice(getMinValue(skus, ProductSkuSaveReqVO::getCostPrice));
        // skus 库存总数
        spu.setStock(getSumValue(skus, ProductSkuSaveReqVO::getStock, Integer::sum));
        // 若是 spu 已有状态则不处理
        if (spu.getStatus() == null) {
            spu.setStatus(ProductSpuStatusEnum.ENABLE.getStatus()); // 默认状态为上架
            spu.setSalesCount(0); // 默认商品销量
            spu.setBrowseCount(0); // 默认商品浏览量
        }
    }
}
